/*
* Wifi 
* scanning wifi message
*/
#include "wifi.h"
#include "ja_process.h"
#include "wifi_scan.h"

int GetSignal(void)
{
	char buf[1024] = {0}, interface[8], status[8], Quality[8];
	int signal;

    FILE *file = fopen("/proc/net/wireless", "r");
    if (file == NULL) {
        printf("Couldn't open file\n");
        return 0;
    }

    while(fgets(buf, sizeof(buf), file)) {
        // printf("%s\n", buf);

		if (strstr(buf, "wlan0")) {
			sscanf(buf, "%s %s %s %d", interface, status, Quality, &signal);
			// printf("interface:%s, status:%s, Quality:%s, signal:%d\n", interface, status, Quality, signal);
		}
    }

	fclose(file);
	return signal;
}

//convert bssid to printable hardware mac address
static const char *bssid_to_string(const uint8_t bssid[BSSID_LENGTH], char bssid_string[BSSID_STRING_LENGTH])
{
	snprintf(bssid_string, BSSID_STRING_LENGTH, "%02x:%02x:%02x:%02x:%02x:%02x",
         bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
	return bssid_string;
}

int JN_Wifi_STA_Search(struct bss_info *bss)
{
	int status;
	struct wifi_scan *wifi = NULL;
	// struct bss_info bss[32];
	char mac[BSSID_STRING_LENGTH];

	wifi = wifi_scan_init("wlan0");
	status = wifi_scan_all(wifi, bss, 32);
	if (status < 0) {
		perror("Unable to get scan data");
	} else {
		for (int i = 0; i < status && i < 32; i++) {
			printf("%s %s signal %d dBm on frequency %u MHz seen %d ms ago status %s\n",
				   bssid_to_string(bss[i].bssid, mac), 
				   bss[i].ssid,  
				   bss[i].signal_mbm/100, 
				   bss[i].frequency,
				   bss[i].seen_ms_ago, 
				   (bss[i].status==BSS_ASSOCIATED ? "associated" : "")
				);
		}
		printf("\n");
	}
	wifi_scan_close(wifi);
	return status;
}

int JN_Wifi_STA_Getstatus(int *connect_status)
{
	char buf[16] = {0};

    FILE *file = fopen("/sys/class/net/wlan0/operstate", "r");
    if (file == NULL) {
        printf("Couldn't open file\n");
        return -1;
    }

	fgets(buf, sizeof(buf), file);
	strtok(buf, "\n");
	// printf("buf: %s\n", buf);
	if (!strcmp(buf, "up")) {
		*connect_status = 1;
	} else {
		*connect_status = 0;
	}

	fclose(file);
	return 0;
}

static void STA_setupSTA(char *essid, char *passwd, char *ConfigueFile)
{
	FILE *fp;
	char str[2048];

	fp = fopen(ConfigueFile, "w+");
	if (fp==NULL) {
		printf("fopen %s error: %s/n", ConfigueFile, strerror(errno));
		return;
	}
	
	//output data
	snprintf(str, sizeof(str) - 1, "ctrl_interface=/var/run/wpa_supplicant\n"
					"update_config=1\n"
					"network={\n"
					"  ssid=\"%s\"\n"
					"  psk=\"%s\"\n"
					"  scan_ssid=1\n"
					"}\n", essid, passwd);
	fputs(str, fp); 

	fclose(fp);
}

int JN_Wifi_STA_Setup(char *essid, char *key)
{
	char str[512] = {0};

	JN_Wifi_Stop("STA");

	STA_setupSTA(essid, key, "/tmp/wpa_supplicant.conf");

	usleep(100000);

	sprintf(str, "wpa_supplicant -D%s -i%s -c%s -B", "nl80211", "wlan0", "/tmp/wpa_supplicant.conf");
	NK_SYSTEM(str);

	usleep(200000);

	snprintf(str, sizeof(str), "udhcpc -q -n -i %s -t 30 -T 1 -s %s", "wlan0", NK_USER_CONFIG_UDHCPC_SCRIPT);
	NK_SYSTEM(str);

	printf("JN_Wifi_Start : STA_openUdhcpc\n");

	return 0;
}

int JN_Wifi_Stop(char *pMode)
{
	if(!strcmp(pMode, "AP")) {
		NK_SYSTEM("kill -9 `pidof hostapd`");
		NK_SYSTEM("kill -9 `pidof udhcpd`");
	}
	if(!strcmp(pMode, "STA")) {
		NK_SYSTEM("kill -9 `pidof wpa_supplicant`");
		NK_SYSTEM("kill -9 `pidof udhcpc`");
	}
	
	return 0;
}

void disconnect_wifi(void)
{
	NK_SYSTEM("wpa_cli -i wlan0 disconnect");
}